package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author 壮哥
 * @Date 2021/9/24/10:03
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //检查是否为登录用户
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请登录");
        }
        //2 条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();

        //分页条件
        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());

        // 文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword());
        // 频道id
        wrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());
        // 文章状态
        wrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        // 发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate());

        // 发布时间 <= 结束时间
        wrapper.le(dto.getEndPubDate()!=null,WmNews::getPublishTime,dto.getEndPubDate());

        // 用户过滤
        wrapper.eq(user.getId()!=null,WmNews::getUserId,user.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getPublishTime);
        // 分页条件构建
        IPage<WmNews> result = page(page, wrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal());
        responseResult.setData(result.getRecords());

        responseResult.setHost(webSite);

        return responseResult;
    }
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        if (StringUtils.isBlank(dto.getContent())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
        }
        Short status = dto.getStatus();
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(status)&&WemediaConstants.WM_NEWS_SINGLE_IMAGE.equals(status)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章状态错误");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        //保存或修改文章

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        List<String> coverList = dto.getImages();
        if (CollectionUtils.isNotEmpty(coverList)){
            wmNews.setImages(imageListToStr(coverList));
        }
        wmNews.setUserId(user.getId());
        saveOrUpdateWmNews(wmNews);
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(status)) {
            return ResponseResult.okResult();
        }

        //保存文章内容与素材的关联关系
        //抽取内容中所有的图片url路径
        List<String> imageList=parseContentImages(wmNews.getContent());
        //保存文章内容和素材的关联关系
        if (CollectionUtils.isNotEmpty(imageList)){
            //引用的素材url路径列表     文章id      引用类型
            saveRelativeInfo(imageList,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }

        //保存文章素材与封面的关联关系
        saveRelativeInfoForCover(dto,wmNews,imageList);
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());

        return ResponseResult.okResult();
    }
    //根据Id查询文章
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }
    //删除文章,
    // 当文章状态为9(已发布)且已上架则不能删除文章，下架状态可以删除，如果是其他状态可以删除
    //删除文章之前需要先把素材与文章的关系删除掉
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())&&wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();

    }
    //文章上下架
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto==null||dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable==null||(!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.修改文章状态，同步到app端（后期做）
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));


        //5. 上下架发送消息通知  用于同步article 及 elasticsearch
        if (wmNews.getArticleId()!=null){
            if (enable.equals(WemediaConstants.WM_NEWS_UP)){
                //上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
                //同步索引库
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,wmNews.getArticleId());
            }else {
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
                //同步索引库
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult();
    }

    //生成封面内容,并保存锋面雨素材的关联关系
    private void saveRelativeInfoForCover(WmNewsDTO dto, WmNews wmNews, List<String> imageList) {
        //入参中封面集合属性
        List<String> images = dto.getImages();
        //如果type为-1,代表根据图片内容集合,自动生成封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            //集合内图片数量大于2, wmNews设置为3  在内容图片集合中,解析前三张图片生成封面
            if (imageList.size()>2){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images=imageList.stream().limit(3).collect(Collectors.toList());
            }
            //集合大于0,小于等于2,wmNews设置为1,在内容图片集合中,解析前1张图片生成封面
            else if (imageList.size()>0&&imageList.size()<=2){
                wmNews.setType(WemediaConstants.WM_IMAGE_REFERENCE);
                imageList.stream().limit(1).collect(Collectors.toList());
            }else{
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images=null;
            }
            if (CollectionUtils.isNotEmpty(images)){
                //如果自动生成封面不为空,将集合转换为字符串拼接
                wmNews.setImages(imageListToStr(images));
            }
            updateById(wmNews);
        }
        //判断最终封面集合是否为空
        if (CollectionUtils.isNotEmpty(images)){
            images=images.stream().map(url -> url.replaceAll(webSite,"")).collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);//保存封面和素材关联关系
        }
    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    private void saveRelativeInfo(List<String> imageList, Integer newsId, Short type) {
        //根据素材url列表+登陆人ID  查询出对应的素材列表
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, imageList)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        if (CollectionUtils.isEmpty(wmMaterials)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联素材不存在");
        }
        //将得到的素材列表转换成map    key:素材url   value:id
        Map<String, Integer> urlAndIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        //遍历 imageList 素材列表,判断每一个素材是否存在,收集id到集合中
        List<Integer> materialIds = new ArrayList<>();
        for (String materialUrl : imageList) {
            if (!urlAndIdMap.containsKey(materialUrl)){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联素材信息不存在");
            }
            materialIds.add(urlAndIdMap.get(materialUrl));
        }
        //调用mapper的批量插入方法,保存关联关系
        wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);
    }

    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSONArray.parseArray(content, Map.class);
        return mapList.stream().filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(map -> (String) map.get("value"))//获得数据中value中得值:图片url路径
                .map(url -> url.replaceAll(webSite,""))//去除路径前缀
                .collect(Collectors.toList());//数据收集到集合

    }



    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setSubmitedTime(new Date());
        if (wmNews.getId()==null){
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        }else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }

    private String imageListToStr(List<String> coverList) {
        return coverList.stream()
                .map(url -> url.replace(webSite,""))
                .collect(Collectors.joining(","));

    }


    @Autowired
    WmNewsMapper wmNewsMapper;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }


    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Autowired
    WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //  通知定时发布文章

        if (status.equals(WmNews.Status.ADMIN_SUCCESS.getCode())){
            long publishTime = wmNews.getPublishTime().getTime();
            long now = new Date().getTime();
            long time = publishTime - now;
            if (time<=0){
                //立即发布
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE,PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,wmNews.getId());
                log.info("立即发布文章通知成功发送，文章id : {}",wmNews.getId());
            }else {
                //延时发布
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE,PublishArticleConstants.PUBLISH_ARTICLE_DEAD_ROUTE_KEY,wmNews.getId(),(message)-> {
                    message.getMessageProperties().setExpiration(String.valueOf(time));
                    return message;
                });
                log.info("延时发布文章通知成功发送，文章id : {} , 延时时间: {}毫秒",wmNews.getId(),time);
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
